import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_app/colors/my_colors.dart';
import 'package:flutter_app/loading/loading_dart.dart';
import 'package:flutter_app/model/TopicInfoModel.dart';
import 'package:flutter_app/screen_page.dart';
import 'package:flutter_app/service/service_method.dart';
import 'package:flutter_app/view/topic_dynamic_page.dart';

class TopicDetailPage extends StatefulWidget {
  final int id;

  TopicDetailPage({Key key, this.id}) : super(key: key);

  @override
  _TopicDetailPageState createState() => _TopicDetailPageState();
}

class _TopicDetailPageState extends State<TopicDetailPage>
    with SingleTickerProviderStateMixin {
  TabController tabController;
  ScrollController _scrollController;

  Brightness mBrightness = Brightness.dark;

  Color mBrightnessColor = Colors.transparent;

  Color mBackColor = Colors.white;
  TopicInfoEntity mEntity;

  getTopicInfo() async {
    var data = {"id": widget.id};
    await requestGet("getTopicInfo", formData: data).then((onValue) {
      TopicInfoModel article = TopicInfoModel.fromJson(onValue);
      setState(() {
        mEntity = article.data;
      });
    });
  }

  @override
  void initState() {
    super.initState();
    this.tabController = TabController(length: 2, vsync: this);
    _scrollController = ScrollController();

    _scrollController.addListener(() {
      if (_scrollController.offset >= 150) {
        setState(() {
          mBrightness = Brightness.light;
          mBrightnessColor = Colors.black;
          mBackColor = Colors.black;
        });
      } else {
        setState(() {
          mBrightness = Brightness.dark;
          mBrightnessColor = Colors.transparent;
          mBackColor = Colors.white;
        });
      }
    });

    getTopicInfo();
  }

  @override
  Widget build(BuildContext context) {
    if (mEntity != null) {
      return Scaffold(
        body: CustomScrollView(
          controller: _scrollController,
          slivers: <Widget>[
            SliverAppBar(
              leading: InkWell(
                onTap: () {
                  Navigator.pop(context);
                },
                child: Icon(
                  Icons.arrow_back_ios,
                  color: mBackColor,
                ),
              ),
              pinned: true,
              brightness: mBrightness,
              centerTitle: true,
              title: Text(
                "${mEntity.name}",
                style: TextStyle(color: mBrightnessColor),
              ),
              elevation: 0,
              //appBar的阴影
              expandedHeight: 250,
              backgroundColor: Colors.white,
              flexibleSpace: FlexibleSpaceBar(
                collapseMode: CollapseMode.pin,
                background: _headWidget(mEntity),
              ),
            ),
            SliverPersistentHeader(
              pinned: true, //是否固定在顶部
              delegate: MySliverPersistentHeaderDelegate(tabController),
            ),
            SliverGrid(
              gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
                maxCrossAxisExtent: 300.0,
                mainAxisSpacing: 10.0,
                crossAxisSpacing: 10.0,
                childAspectRatio: 1.5,
              ),
              delegate: SliverChildBuilderDelegate(
                (BuildContext context, int index) {
                  return Container(
                    alignment: Alignment.center,
                    color: Colors.teal[100 * (index % 9)],
                    child: Text('grid item $index'),
                  );
                },
                childCount: 10,
              ),
            ),
          ],
        ),
      );
    } else {
      return loadWidget();
    }
  }

  final List<Widget> topicDynamicPage = [
    TopicDynamicPage(),
    TopicDynamicPage()
  ];

  Widget _headWidget(TopicInfoEntity mEntity) {
    return Stack(
      overflow: Overflow.clip,
      children: <Widget>[
        Image.network(
          "${mEntity.imgUrl}",
          width: double.infinity,
          height: double.infinity,
          fit: BoxFit.cover,
        ),
        Container(
          height: double.infinity,
          width: double.infinity,
          color: MyColors.black_bright_bg,
        ),
        Positioned(
            left: width(15),
            top: height(86),
            child: Container(
              width: width(360),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Text(
                    "${mEntity.name}",
                    style: TextStyle(fontSize: sp(20), color: Colors.white),
                    overflow: TextOverflow.ellipsis,
                    maxLines: 1,
                  ),
                  SizedBox(height: height(10)),
                  Container(
                    height: height(22),
                    padding: EdgeInsets.all(3),
                    decoration: BoxDecoration(color: MyColors.black_bright_bg),
                    child: Text(
                        "${mEntity.wineTalkNum}条动态·${mEntity.totalOpenTimes}次浏览数",
                        style: TextStyle(fontSize: sp(14), color: Colors.white),
                        overflow: TextOverflow.ellipsis,
                        maxLines: 1),
                  ),
                  SizedBox(height: height(12)),
                  Text(
                    "${mEntity.description}",
                    style: TextStyle(fontSize: sp(15), color: Colors.white),
                    overflow: TextOverflow.ellipsis,
                    maxLines: 3,
                  )
                ],
              ),
            )),
      ],
    );
  }
}


//中间部分
class MySliverPersistentHeaderDelegate extends SliverPersistentHeaderDelegate {
  final TabController _tabController;

  MySliverPersistentHeaderDelegate(this._tabController);

  @override
  Widget build(BuildContext context, double shrinkOffset,
      bool overlapsContent) {
    return Container(
      width: double.infinity,
      height: height(44),
      padding: EdgeInsets.only(left: width(70), right: width(70)),
      color: Colors.white,
      child: TabBar(
          controller: _tabController,
          unselectedLabelColor: Colors.black54,
          unselectedLabelStyle: TextStyle(fontSize: sp(12)),
          labelColor: Colors.pink,
          labelStyle: TextStyle(fontSize: sp(21)),
          indicatorColor: Colors.transparent,
          labelPadding: EdgeInsets.all(0),
          //文字显示不全这里设置成0，即代表不加padding
          indicatorSize: TabBarIndicatorSize.tab,
          tabs: tabs),
    );
  }

  @override
  double get maxExtent => height(44);

  @override
  double get minExtent => height(44);

  @override
  bool shouldRebuild(SliverPersistentHeaderDelegate oldDelegate) =>
      false; // 如果内容需要更新，设置为true
}

//下面列表
class MySliverChildBuilderDelegate extends SliverChildBuilderDelegate {
  MySliverChildBuilderDelegate(builder) : super(builder);

}

List<Widget> tabs = [
  Text(
    "最新",
  ),
  Text(
    "最热",
  ),
];
